
//验证邮件的合理性
function verifyAddress(value){
    var regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    if (regex.test(value)) {
        return true;
    }
    else {
        return false;
    }
}

//过滤掉特殊字符
function stripscript(value){
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】 ‘；：”“’。，、？]");
    var rs = "";
    for (var i = 0; i < value.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}
var tip="6为最高级别";
var ds = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: 'user_list.action',
        method: 'POST'
    }),
    reader: new Ext.data.JsonReader({
        root: 'humans',
        totalProperty: 'totalCount'
    }, [{
        name: 'userId',
        mapping: 'userId',
        type: 'long',
        hidden: 'true'
    }, {
        name: 'userName',
        mapping: 'userName',
        type: 'string'
    }, {
        name: 'gender',
        mapping: 'gender',
        type: 'short'
    }, {
        name: 'status',
        mapping: 'status',
        type: 'short'
    }, {
        name: 'securityGrade',
        mapping: 'securityGrade',
        type: 'short'
    }, {
        name: 'ability',
        mapping: 'ability',
        type: 'short'
    }, {
        name: 'mobilePhone',
        mapping: 'mobilePhone',
        type: 'string'
    }, {
        name: 'email',
        mapping: 'email',
        type: 'string'
    }, {
        name: 'operation',
        type: 'string'
    }])
});

var cm_user = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
    header: "用户名",
    width:200,
    dataIndex: 'userName',
    sortable: true,
    renderer: function(value, metadata, record){
        return "<a href = 'javascript:void(0)' onclick=javascript:showUserView('" +
        record.data.userId +
        "')> " +
        escapeHTML(value) +
        " </a>";
    }
}, {
    header: "性别",
    width: 80,
    dataIndex: 'gender',
    sortable: true,
    renderer: function(value, metadata, record){
        if (value == 1) {
            return '男';
        }
        else {
            return '女';
        };
            }
}, {
    header: "状态",
    width: 80,
    dataIndex: 'status',
    sortable: true,
    renderer: function(value, metadata, record){
        if (value == 0) {
            return '在职';
        }
        else {
            return '离职';
        };
            }
}, {
    header: "涉密级别",
    width: 80,
    dataIndex: 'securityGrade',
    sortable: true,
    renderer: function(value, metadata, record){
        if (value == 1) {
            return '普通';
        }
        else 
            if (value == 2) {
                return '秘密';
            }
            else 
                if (value == 3) {
                    return '机密';
                }
                else {
                    return '绝密';
                };
            }
}, {
    header: "能力级别",
    width: 80,
    dataIndex: 'ability',
    renderer: function(value,metadata,record){
		metadata.attr =' ext:qtip="' + tip + '"';
		return "<font color='#2B76C8'>"+value+"</font>";
    },
    sortable: true
}, {
    header: "手机号",
    width: 120,
    dataIndex: 'mobilePhone',
    sortable: true
}, {
    header: "邮箱",
    width: 160,
    dataIndex: 'email',
    sortable: true
}, {
    header: "操作",
    width: 120,
    dataIndex: 'operation',
    sortable: true,
    renderer: function(value, metadata, record){
    
        if (record.data.status == 0) {
            if (record.data.userName == 'admin' || record.data.userName == userName) {
                return "<font color='#cccccc'>禁用</font> &nbsp;&nbsp;<a href='javascript:void(0)' onclick=javascript:modifyUserInfo('" +
                record.data.userId +
                "')>编辑</a>";
            }
            else {
                return "<a href = 'javascript:void(0)' id = '" +
                record.data.userId +
                "' name='close' onclick=javascript:closeUserStatus('" +
                record.data.userId +
                "')>禁用</a> &nbsp;&nbsp;<a href='javascript:void(0)' onclick=javascript:modifyUserInfo('" +
                record.data.userId +
                "')>编辑</a>";
            }
        }
        else {
            return "<a href = 'javascript:void(0)' id = '" +
            record.data.userId +
            "' name='open' onclick=javascript:openUserStatus('" +
            record.data.userId +
            "')>启用</a> &nbsp;&nbsp;<a href='javascript:void(0)' onclick=javascript:modifyUserInfo('" +
            record.data.userId +
            "')>编辑</a>";
        }
    }
}]);

var select_user = new Ext.Button({
    text: '查找用户',
    width: 110,
    iconCls: 'user_search',
    handler: function(){
        userForm = new Ext.form.FormPanel({
            labelAlign: 'right',
            labelWidth: 100,
            frame: true,
            width: 400,
            store: ds,
            items: [{
                xtype: 'textfield',
                name: 'userName',
                fieldLabel: '用户名',
                itemCls: 'form_text'
            }, {
                xtype: 'panel',
                layout: "column",
                isFormField: true,
                fieldLabel: '状态',
                itemCls: 'clear',
                items: [{
                    xtype: "checkbox",
                    boxLabel: "在职",
                    name: "status",
                    inputValue: "0"
                }, {
                    xtype: "checkbox",
                    boxLabel: "离职",
                    name: "status",
                    inputValue: "1"
                }]
            }, {
                xtype: 'panel',
                layout: "column",
                isFormField: true,
                fieldLabel: '涉密级别',
                items: [{
                    xtype: "checkbox",
                    boxLabel: "普通",
                    name: "securityGrade",
                    inputValue: "1"
                }, {
                    xtype: "checkbox",
                    boxLabel: "秘密",
                    name: "securityGrade",
                    inputValue: "2"
                }, {
                    xtype: "checkbox",
                    boxLabel: "机密",
                    name: "securityGrade",
                    inputValue: "3"
                }, {
                    xtype: "checkbox",
                    boxLabel: "绝密",
                    name: "securityGrade",
                    inputValue: "5"
                }]
            }, {
                xtype: 'panel',
                layout: "column",
                isFormField: true,
                fieldLabel: '能力级别',
                items: [{
                    xtype: "checkbox",
                    boxLabel: "1",
                    name: "ability",
                    inputValue: "1"
                }, {
                    xtype: "checkbox",
                    boxLabel: "2",
                    name: "ability",
                    inputValue: "2"
                }, {
                    xtype: "checkbox",
                    boxLabel: "3",
                    name: "ability",
                    inputValue: "3"
                }, {
                    xtype: "checkbox",
                    boxLabel: "4",
                    name: "ability",
                    inputValue: "4"
                }, {
                    xtype: "checkbox",
                    boxLabel: "5",
                    name: "ability",
                    inputValue: "5"
                }, {
                    xtype: "checkbox",
                    boxLabel: "6",
                    name: "ability",
                    inputValue: "6"
                }]
            }, {
                xtype: 'panel',
                layout: "column",
                isFormField: true,
                fieldLabel: '性别',
                items: [{
                    xtype: "checkbox",
                    boxLabel: "男",
                    name: "gender",
                    inputValue: "1"
                }, {
                    xtype: "checkbox",
                    boxLabel: "女",
                    name: "gender",
                    inputValue: "2"
                }]
            }],
            buttons: [{
                text: '查找',
                type: 'submit',
                handler: function(){
                    ds.baseParams = userForm.getForm().getValues();
                    ds.load({
                        params: {
                            start: 0,
                            limit: 20
                        }
                    });
                    window_select_user.close();
                }
            }, {
                text: '取消',
                type: 'submit',
                handler: function(){
                    window_select_user.close();
                }
            }]
        });
        
        var window_select_user = new Ext.Window({
            title: '查找用户',
            iconCls: 'user_search',
            width: 400,
            resizable: false,
            autoHeight: true,
            constrain: true,
            modal: true,
            closeAction: 'hide',
            closable: false,
            items: userForm
        }).show();
    }
});

var defaultRadioBox = new Array();
var userRoleBox = new Array();
var roleCheckbox = new Array();

var add_user = new Ext.Button({
    text: '新增用户',
    width: 100,
    iconCls: 'user_add',
    handler: function(){
    
        var tab_role = new Ext.Panel({
            title: '拥有角色（可多选）',
            layout: 'column',
            id: 'tab_role',
            plain: true,
            frame: true,
            cls: "clear_l",
            defaults: {
                autoHeight: true,
                autoWidth: true
            }
        });
        
        var tab_defaultRole = new Ext.Panel({
            title: '默认角色',
            layout: 'column',
            id: 'tab_defaultRoleRole',
            plain: true,
            frame: true,
            cls: "clear_l",
            defaults: {
                autoHeight: true,
                autoWidth: true
            },
            hidden: 'true'
        });
        
        Ext.Ajax.request({
            url: 'user_role_list.action',
            method: 'post',
            success: function(resp, opts){
                var respText = Ext.util.JSON.decode(resp.responseText);
                if (respText.success) {
                    var roles = respText.roles;
                    var roleCheckbox = new Array();
                    for (var i = 0; i < roles.length-1; i++) {
                        defaultRadioBox[i] = new Ext.form.Radio({
                            boxLabel: roles[i].roleName,
                            columnWidth: .2,
                            name: 'default_RoleId',
                            id: roles[i].roleId,
                            inputValue: roles[i].roleId,
                            hidden: 'true'
                        });
                    }for(var i = 0; i < roles.length; i++)  { 
                        roleCheckbox[i] = new Ext.form.Checkbox({
                            boxLabel: roles[i].roleName,
                            name: 'roleId',
                            inputValue: roles[i].roleId,
                            listeners: {
                                'check': function(obj, checked){
                    				if (checked) {
                                        Ext.getCmp('tab_defaultRoleRole').show();
                                        Ext.getCmp(obj.getRawValue()).show();
                                        // Ext.MessageBox.alert('消息','在弹出的单选框中选择默认角色');
                                    }else {
                                        Ext.getCmp(obj.getRawValue()).setValue(false);
                                        Ext.getCmp(obj.getRawValue()).hide();
                                    }
                                }
                            }
                        
                        });
                        
                    }
                    tab_role.add(roleCheckbox);
                    tab_defaultRole.add(defaultRadioBox);
                    tab_role.doLayout();
                    tab_defaultRole.doLayout();               //重新渲染Panel
                }
                else {
                    Ext.Msg.show({
                        title: '错误提示',
                        msg: '获取用户角色失败!',
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR,
                        width: 200
                    });
                }
            },
            failure: function(){
                Ext.Msg.show({
                    title: '错误提示',
                    msg: '获取用户角色失败!',
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR,
                    width: 200
                });
            }
        });
        var addUserForm = new Ext.form.FormPanel({
            labelAlign: 'right',
            labelWidth: 100,
            frame: true,
            width: 596,
            id: 'addUser',
            items: [{
                layout: 'fit',
                items: [{
                    title: '基本信息',
                    autoHeight: true,
                    xtype: 'fieldset',
                    layout: 'form',
                    xtype: 'fieldset',
                    items: [{
                        xtype: 'textfield',
                        name: 'userName',
                        id: 'userName',
                        allowBlank: false,
                        fieldLabel: '用户名',
                        validator: function(value){
                            if (value.indexOf('<') != -1 || value.indexOf('>') != -1) {
                                return false;
                            }
                            else {
                                var regex = /[\S]/;
                                return regex.test(value);
                            }
                        },
                        invalidText: '用户名不合法:不能带<>等特殊符号且不能为空',
                        maxLength: 20,
                        maxLengthText : '用户名最大长度不能超过20' ,
                        itemCls: 'form_text',
                        listeners : {
                        	"change" : function(){
                        		Ext.Ajax.request({
					    			url : 'user_list.action',
					    			method : 'post',
					    			params : {
					    				start: 0,
						                limit: 20,
						                userName: '',
						                status: '',
						                securityGrade: '',
						                ability: '',
						                gender: ''
					    			},
					    			success : function(resp, opts) {
										var respText = Ext.util.JSON.decode(resp.responseText);
										var humans = respText.humans;
										for(var i = 0;i < humans.length;i++)
										{
											if(humans[i].userName == Ext.getCmp('userName').getValue())
											{
													Ext.Msg.show({
			                                        title: '错误提示',
			                                        msg: '用户名已存在，请重新输入！',
			                                        buttons: Ext.Msg.OK,
			                                        icon: Ext.Msg.INFO,
			                                        width: 200
			                                    });
											}
										}
					    			}
					    		});
                        	}
                        }
                    }, {
                        xtype: 'textfield',
                        name: 'user.email',
                        validator: function(value){
                            return verifyAddress(value);
                        },
                        invalidText: '输入的邮箱格式不合法,格式如:Json@163.com',
                        allowBlank: false,
                        fieldLabel: '邮箱',
                        itemCls: 'form_text',
                        maxLength: 30,
                        maxLengthText : '邮箱最大长度不能超过30' 
                    }, {
                        fieldLabel: '手机号',
                        xtype: 'textfield',
                        regex:/^1[0-9]{10}$/,
                        regexText:'输入的手机号码不合法,格式如:159****5678(11位)',
                        allowBlank: false,
                        name: 'user.mobilePhone',
                        itemCls: 'form_text'
                    }, {
                        fieldLabel: '电话',
                        xtype: 'textfield',
                        regex:/^\d{4}-?\d{7}$|^[0-9]{4}-?[0-9]{8}$|^[0-9]{3}-?[0-9]{8}$/,
                        regexText:'输入的电话格式不合法,格式如:区号-号码[3-8,4-7,4-8]',
                        allowBlank: false,
                        name: 'user.telephone',
                        itemCls: 'form_text'  
                    }, {
                        xtype: 'textfield',
                        name: 'password',
                        id: 'password',
//                        allowBlank: false,
                        fieldLabel: '密码',
                        inputType: 'password',
                        regex: /^[A-Za-z0-9]{6,11}$/,
                        regexText: '密码只能为6~11位的数字或字母组合',
                        itemCls: 'form_text'
                    }, {
                        xtype: 'textfield',
                        name: 'confirmPassword',
                        id: 'confirmPassword',
//                        allowBlank: false,
                        fieldLabel: '确认密码',
                        regex: /^[A-Za-z0-9]{6,11}$/,
                        regexText: '密码只能为6~11位的数字或字母组合',
                        inputType: 'password',
                        itemCls: 'form_text',
                        listeners : {
                        	"blur" : function(){
                        		var password = Ext.getCmp('password').getValue();
                        		var confirmPassword = Ext.getCmp('confirmPassword').getValue();
			                    if (confirmPassword != password) {
			                        Ext.Msg.show({
			                            title: '错误提示',
			                            msg: '确认密码必须和密码一致！',
			                            buttons: Ext.Msg.OK,
			                            icon: Ext.Msg.INFO,
			                            width: 200
			                        });
			                        return;
			                    }
                        	}
                        }
                    }]
                }]
            }, {
				layout: 'fit',
				items: [{
					title: '详细信息',
					autoHeight: true,
					xtype: 'fieldset',
					layout: 'form',
					xtype: 'fieldset',
					items: [{
						xtype: 'combo',
						store: new Ext.data.SimpleStore({
							data: [['1', '男'], ['2', '女']],
							fields: ['value', 'text']
						}),
						
						hiddenName: 'user.gender',
						allowBlank: false,
						editable: false,
						fieldLabel: '性别',
						emptyText: '请选择',
						mode: 'local',
						triggerAction: 'all',
						valueField: 'value',
						displayField: 'text',
						itemCls: 'form_text'
					}, {
						xtype: 'combo',
						store: new Ext.data.SimpleStore({
							data: [['专科', '专科'], ['本科', '本科'], ['硕士', '硕士'],['博士', '博士'],['其他', '其他']],
							fields: ['value', 'text']
						}),
						editable: false,
						name: 'academyDegree',
						fieldLabel: '学历',
						emptyText: '请选择',
						mode: 'local',
						triggerAction: 'all',
						valueField: 'value',
						displayField: 'text',
						itemCls: 'form_text'
					}, {
						xtype: 'combo',
						store: new Ext.data.SimpleStore({
							data: [['1', '普通'], ['2', '秘密'], ['3', '机密'], ['5', '绝密']],
							fields: ['value', 'text']
						}),
						
						hiddenName: 'user.securityGrade',
						allowBlank: false,
						editable: false,
						fieldLabel: '涉密级别',
						emptyText: '请选择',
						mode: 'local',
						triggerAction: 'all',
						valueField: 'value',
						displayField: 'text',
						itemCls: 'form_text'
					}, {
						xtype: 'combo',
						store: new Ext.data.SimpleStore({
							data: [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']],
							fields: ['value', 'text']
						}),
						
						hiddenName: 'user.ability',
						allowBlank: false,
						editable: false,
						fieldLabel: '能力级别',
						emptyText: '6为最高级别',
						mode: 'local',
						triggerAction: 'all',
						valueField: 'value',
						displayField: 'text',
						itemCls: 'form_text'
					}, {
						xtype: 'datefield',
						name: 'birthday',
						editable: false,
						emptyText: '请选择',
						fieldLabel: '出生日期',
						format: 'Y-m-d',
						itemCls: 'form_text',
						minValue: '1950-01-01',
						maxValue: new Date().format('Y-m-d'),
						value: '1980-01-01'
					}]
				}]
			}, tab_role, tab_defaultRole],
            buttons: [{
                text: '增加',
                type: 'submit',
                handler: function(){
                    var flag = false;
                    for (var i = 0; i < defaultRadioBox.length; i++) {
                        if (defaultRadioBox[i].checked) {
                            flag = true;
                        }
                    }
                    
                    if (flag == false) {
                        Ext.Msg.show({
                            title: '错误提示',
                            msg: '必须选择一个默认角色',
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.INFO,
                            width: 200
                        });
                        return;
                    }
                    
                    var password = Ext.getCmp('password').getValue();
                    var confirmPassword = Ext.getCmp('confirmPassword').getValue();
                    if (confirmPassword != password) {
                        Ext.Msg.show({
                            title: '错误提示',
                            msg: '确认密码必须和密码一致！',
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.INFO,
                            width: 200
                        });
                        return;
                    }
                    
                    if (addUserForm.form.isValid()) {
                        addUserForm.form.doAction('submit', {
                            url: 'user_add.action',// 文件路径
                            method: 'post',// 提交方法post或get
                            params: '',
                            success: function(form, action){
                                if (action.result.msg == 'wrong') {
                                    Ext.Msg.show({
                                        title: '错误提示',
                                        msg: '用户名已存在，请重新输入！',
                                        buttons: Ext.Msg.OK,
                                        icon: Ext.Msg.ERROR,
                                        width: 200
                                    });
                                }
                                else 
                                    if (action.result.msg == 'ok') {
                                        Ext.Msg.show({
                                            title: '消息',
                                            msg: '添加成功！',
                                            buttons: Ext.Msg.OK,
                                            icon: Ext.Msg.INFO,
                                            width: 200
                                        });
                                        window_add_user.remove(Ext.getCmp('addUser'));
                                        window_add_user.close();
                                        ds.reload();
                                    }
                            },
                            failure: function(form, action){
                                if (action.failureType == 'server') {
                                    Ext.Msg.show({
                                        title: '错误',
                                        msg: '增加失败！',
                                        buttons: Ext.Msg.OK,
                                        icon: Ext.Msg.INFO,
                                        width: 200
                                    });
                                }
                                else 
                                    if (action.failureType == 'connect') {
                                        Ext.Msg.show({
											title : '连接错误',
											msg : '指定路径连接错误!',
											buttons : Ext.Msg.OK,
											icon : Ext.Msg.ERROR,
											width : 200
										});
                                    }
                                    else 
                                        if (action.failureType == 'client') {
                                            Ext.Msg.show({
												title : '提示',
												msg : '数据错误，非法提交',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                                        else {
                                            Ext.Msg.show({
												title : '警告',
												msg : '服务器数据传输错误',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                            }
                        });
                    }
                }
            }, {
                text: '重置',
                type: 'reset',
                handler: function(){
                    addUserForm.form.reset();
                }
                
            }, {
                text: '取消',
                handler: function(){
                    window_add_user.remove(Ext.getCmp('addUser'));
                    window_add_user.close();
                }
            }]
        });
        
        var window_add_user = new Ext.Window({
            title: '新增用户',
            width: 610,
            iconCls: 'user_add',
            resizable: false,
            constrain: true,
            autoHeight : true,
            modal: true,
            closeAction: 'hide',
            closable: false,
            items: addUserForm,
            constrain: true,
            x : 350,
            y : 0
        }).show();
        
    }
    
});

var list_allUsers = new Ext.Button({

    text: '列出所有用户',
    width: 120,
    iconCls: 'refresh',
    handler: function(){
        ds.baseParams = null;
        ds.load({
            params: {
                start: 0,
                limit: 20,
                userName: '',
                status: '',
                securityGrade: '',
                ability: '',
                gender: ''
            }
        });
    }
    
});

var resetPassword = new Ext.Button({
    text: '重置密码',
    iconCls: "rest_password",
    width: 120,
    handler: function(){
        var resetPasswordForm = new Ext.form.FormPanel({
            labelAlign: 'right',
            labelWidth: 80,
            frame: true,
            width: 320,
            id: 'resetPassword',
            items: [{
                xtype: 'textfield',
                name: 'userName',
                allowBlank: false,
                fieldLabel: '用户名',
                validator: function(value){
                    if (value.indexOf('<') != -1 || value.indexOf('>') != -1) {
                        return false;
                    }
                    else {
                        var regex = /[\S]/;
                        return regex.test(value);
                    }
                },
                invalidText: '用户名不合法:不能带<>等特殊符号且不能为空',
                itemCls: 'form_text'
            }, {
                xtype: 'textfield',
                name: 'newPassword',
                id: 'newPassword',
//                allowBlank: false,
                fieldLabel: '重置密码',
                inputType: 'password',
                regex: /^[A-Za-z0-9]{6,11}$/,
                regexText: '密码只能为6~11位的数字或字母组合',
                itemCls: 'form_text'
            }, {
                xtype: 'textfield',
                name: 'confirmPasswordTwo',
                id: 'confirmPasswordTwo',
//                allowBlank: false,
                fieldLabel: '确认密码',
                regex: /^[A-Za-z0-9]{6,11}$/,
                regexText: '密码只能为6~11位的数字或字母组合',
                inputType: 'password',
                itemCls: 'form_text'
            }],
            buttons: [{
                text: '修改',
                type: 'submit',
                handler: function(){
                
                    var newPassword = Ext.getCmp('newPassword').getValue();
                    var confirmPasswordTwo = Ext.getCmp('confirmPasswordTwo').getValue();
                    if (confirmPasswordTwo != newPassword) {
                        Ext.Msg.show({
                            title: '错误提示',
                            msg: '确认密码必须和重置密码一致！',
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.INFO,
                            width: 200
                        });
                        return;
                    }
                    
                    if (resetPasswordForm.form.isValid()) {
                        resetPasswordForm.form.doAction('submit', {
                            url: 'user_resetPassword_edit.action',// 文件路径
                            method: 'post',// 提交方法post或get
                            params: '',
                            success: function(form, action){
                                if (action.result.msg == 'wrong') {
                                    Ext.Msg.show({
                                        title: '错误提示',
                                        msg: '不存在此用户',
                                        buttons: Ext.Msg.OK,
                                        icon: Ext.Msg.ERROR,
                                        width: 200
                                    });
                                }
                                else 
                                    if (action.result.msg == 'ok') {
                                        Ext.Msg.show({
                                            title: '消息',
                                            msg: '重置密码成功！',
                                            buttons: Ext.Msg.OK,
                                            icon: Ext.Msg.INFO,
                                            width: 200
                                        });
                                        window_reset_password.remove(Ext.getCmp('resetPassword'));
                                        window_reset_password.close();
                                        ds.reload();
                                    }
                            },
                            failure: function(form, action){
                                if (action.failureType == 'server') {
                                    Ext.Msg.show({
                                        title: '错误',
                                        msg: '重置密码失败！',
                                        buttons: Ext.Msg.OK,
                                        icon: Ext.Msg.INFO,
                                        width: 200
                                    });
                                }
                               else 
                                    if (action.failureType == 'connect') {
                                        Ext.Msg.show({
											title : '连接错误',
											msg : '指定路径连接错误!',
											buttons : Ext.Msg.OK,
											icon : Ext.Msg.ERROR,
											width : 200
										});
                                    }
                                    else 
                                        if (action.failureType == 'client') {
                                            Ext.Msg.show({
												title : '提示',
												msg : '数据错误，非法提交',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                                        else {
                                            Ext.Msg.show({
												title : '警告',
												msg : '服务器数据传输错误',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                            }
                        });
                    }
                }
            }, {
                text: '重置',
                type: 'reset',
                handler: function(){
                    resetPasswordForm.form.reset();
                }
            }, {
                text: '取消',
                handler: function(){
                    window_reset_password.remove(Ext.getCmp('resetPassword'));
                    window_reset_password.close();
                }
            }]
        });
        
        var window_reset_password = new Ext.Window({
            title: '重置密码',
            width: 320,
            iconCls: "rest_password",
            resizable: false,
            constrain: true,
            autoHeight: true,
            modal: true,
            closeAction: 'hide',
            closable: false,
            items: resetPasswordForm,
            constrain: true
        }).show();
    }
    
});

var grid = new Ext.grid.GridPanel({
    title: '当前位置：用户管理',
    loadMask: {
        msg: '数据加载中...'
    },
    ds: ds,
    store: ds,
    region: 'center',
    autoScroll: true,
    cm: cm_user,
//    autoExpandColumn: 1,
    tbar: [select_user, add_user, list_allUsers, resetPassword],
    bbar: new Ext.PagingToolbar({
        pageSize: 20,
        store: ds,
        displayInfo: true,
        beforePageText: '第',
        afterPageText: '页-共{0}页',
        displayMsg: '显示{0} - {1} 条  共 {2} 条',
        emptyMsg: "没有记录"
    })
});
ds.load({
    params: {
        start: 0,
        limit: 20
    }
});

window.closeUserStatus = function(needParam){
    Ext.Ajax.request({
        url: "user_status_close.action",
        method: 'post',
        params: {
            userId: needParam
        },
        success: function(resp, opts){
            var respText = Ext.util.JSON.decode(resp.responseText);
            if (respText.success) {
                if (respText.msg == 'wrong') {
                    Ext.Msg.show({
                        title: '错误提示',
                        msg: '该用户有未完成的稿件工作，不能关闭！',
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR,
                        width: 200
                    });
                }
                else 
                    if (respText.msg == 'ok') {
                        ds.reload();
                    }
            }
            else {
                Ext.Msg.show({
                    title: '错误提示',
                    msg: respText.msg,
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR,
                    width: 200
                });
            }
        },
        failure: function(){
            Ext.Msg.show({
                title: '错误提示',
                msg: '修改失败！',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR,
                width: 200
            });
        }
        
    });
};

window.openUserStatus = function(needParam){
    Ext.Ajax.request({
        url: "user_status_open.action",
        method: 'post',
        params: {
            userId: needParam
        },
        success: function(resp, opts){
            var respText = Ext.util.JSON.decode(resp.responseText);
            if (respText.success) {
                ds.reload();
            }
            else {
                Ext.Msg.show({
                    title: '错误提示',
                    msg: '修改状态失败！',
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR,
                    width: 200
                });
            }
        },
        failure: function(){
            Ext.Msg.show({
                title: '错误提示',
                msg: '修改状态失败！',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR,
                width: 200
            });
        }
    });
};

window.showUserView = function(needParam){
    Ext.Ajax.request({
        url: 'user_view.action',
        method: 'post',
        params: {
            userId: needParam
        },
        success: function(resp, opts){
            var respText = Ext.util.JSON.decode(resp.responseText);
            var status = '';
            var securityGrade = '';
            var gender = '';
            var userRoles = respText.userRoles;
            var userRoleNames = '';
            for (var i = 0; i < userRoles.length - 1; i++) {
                userRoleNames = userRoleNames + userRoles[i].roleName + ',';
            }
            userRoleNames += userRoles[userRoles.length - 1].roleName;
            if (respText.user.status == 0) {
                status = '在职';
            }
            else {
                status = '离职';
            }
            if (respText.user.gender == 1) {
                gender = '男';
            }
            else {
                gender = '女';
            }
            if (respText.user.securityGrade == 1) {
                securityGrade = '普通';
            }
            else 
                if (respText.user.securityGrade == 2) {
                    securityGrade = '秘密';
                }
                else 
                    if (respText.user.securityGrade == 3) {
                        securityGrade = '机密';
                    }
                    else {
                        securityGrade = '绝密';
                    }
            
            if (respText.success) {
                var userinfo_window = new Ext.Window({
                    title: '用户详情',
                    width: 600,
                    iconCls: 'user_manager',
                    resizable: false,
                    constrain: true,
                    autoHeight: true,
                    modal: true,
                    closeAction: 'hide',
                    closable: false,
                    items: [new Ext.FormPanel({
                        border: false,
                        frame: true,
                        labelAlign: 'right',
                        labelWidth: 100,
                        defaults: {
                            itemCls: 'form_text unedit',
                            msgTarget: 'side'
                        },
                        defaultType: 'textfield',
                        items: [{
                            fieldLabel: '用户名',
                            value: respText.user.userName,
                            readOnly: true
                        }, {
                            fieldLabel: '状&nbsp;&nbsp;&nbsp;态',
                            value: status,
                            readOnly: true
                        }, {
                            fieldLabel: '涉密级别',
                            value: securityGrade,
                            readOnly: true
                        }, {
                            fieldLabel: '能力级别',
                            value: respText.user.ability,
                            readOnly: true
                        }, {
                            fieldLabel: '电&nbsp;&nbsp;&nbsp;话',
                            value: respText.user.telephone,
                            readOnly: true
                        }, {
                            fieldLabel: '手机号',
                            value: respText.user.mobilePhone,
                            readOnly: true
                        }, {
                            fieldLabel: '邮&nbsp;&nbsp;&nbsp;箱',
                            value: respText.user.email,
                            readOnly: true
                        }, {
                            fieldLabel: '性&nbsp;&nbsp;&nbsp; 别',
                            value: gender,
                            readOnly: true
                        }, {
                            fieldLabel: '出生日期',
                            value: respText.user.birthday,
                            readOnly: true
                        }, {
                            fieldLabel: '最高学历',
                            value: respText.user.academyDegree,
                            readOnly: true
                        }, {
                            fieldLabel: '创建时间',
                            value: formatTime(respText.user.createdTimestamp, "", ""),
                            readOnly: true
                        }, {
                            fieldLabel: '最后修改人',
                            value: respText.user.lastModifierName,
                            readOnly: true
                        }, {
                            fieldLabel: '最后修改时间',
                            value: formatTime(respText.user.lastModified, "", ""),
                            readOnly: true
                        }, {
                            fieldLabel: '默认角色',
                            value: respText.defaultRole.roleName,
                            readOnly: true
                        }, {
                            fieldLabel: '拥有角色',
                            xtype: 'textarea',
                            value: userRoleNames,
                            itemCls: 'form_long clear unedit',
                            readOnly: true,
                            width: 426
                        }],
                        buttons: [{
                            text: '关闭',
                            handler: function(){
                                userinfo_window.close();
                            }
                        }]
                    })]
                
                }).show();
            }
            else {
                Ext.Msg.show({
                    title: '错误提示',
                    msg: '查看用户详情失败！',
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR,
                    width: 200
                });
            }
        },
        failure: function(){
            Ext.Msg.show({
                title: '错误提示',
                msg: '查看用户详情失败！',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR,
                width: 200
            });
        }
    });
};

window.modifyUserInfo = function(needParam){
    var user_role = new Ext.Panel({
        title: '拥有角色（可多选）',
        labout: 'form',
        id: 'user_role',
        plain: true,
        constrain: true,
        frame: true,
        cls: 'clear_l',
        layout: "column",
        defaults: {
            autoHeight: true,
            autoWidth: true
        }
    });
    
    var user_defaultRole = new Ext.Panel({
        title: '默认角色',
        labout: 'form',
        id: 'user_defaultRole',
        plain: true,
        frame: true,
        cls: 'clear_l',
        layout: "column",
        defaults: {
            autoHeight: true,
            autoWidth: true
        }
    });
    
    Ext.Ajax.request({
        url: 'user_view.action',
        method: 'post',
        params: {
            userId: needParam
        },
        success: function(resp, opts){
            var respText = Ext.util.JSON.decode(resp.responseText);
            if (respText.success) {
                var roles = respText.roles;
                var userRoles = respText.userRoles;
                var defaultRole = respText.defaultRole;
                var rolesOfUser = new Array();
                for (var i = 0; i < roles.length; i++) {
                    roleCheckbox[i] = new Ext.form.Checkbox({
                        boxLabel: roles[i].roleName,
                        columnWidth: .2,
                        name: 'roleId',
                        inputValue: roles[i].roleId,
                        listeners: {
                            'check': function(obj, checked){
                                var ff = user_defaultRole.findByType('radio');
                                var dd = '';
                                for (var z = 0; z < roles.length; z++) {
                                    if ((roles[z].roleId == obj.getRawValue())&&(obj.getRawValue()!="281474976710665")) {   // getRawValue()返回可能无效的原始值。要返回正式的值应该使用getValue()
                                        dd = roles[z].roleName;
                                    }
                                }//录入人的ID为  281474976710665
                                var aa; 
                                if(dd!=''){
                                	aa = new Ext.form.Radio({
                                        boxLabel: dd,
                                        columnWidth: .2,
                                        name: 'default_RoleId',
                                        inputValue: obj.getRawValue(),
                                        id: obj.getRawValue()
                                    });
                                } 
                                if (checked) {
                                    var flag2 = 0;
                                    for (var t = 0; t < ff.length; t++) {
                                        if (obj.getRawValue() == ff[t].roleId) {
                                            flag2++;
                                        }
                                    }
                                    if (flag2 == 0 ) {
                                        user_defaultRole.add(aa);
                                        userRoleBox.push(aa);
                                    }
                                }
                                else {
                                    user_defaultRole.remove(aa);
                                    var j = '';
                                    
                                    for (var m = 0; m < userRoles.length; m++) {
                                        if (obj.getRawValue() == userRoles[m].roleId) {
                                            j = m;
                                        }
                                    }
                                    userRoleBox.splice(j, 1);
                                    
                                }
                                
                                
                                user_defaultRole.doLayout();
                            }
                        }
                    });
                    
                    user_role.add(roleCheckbox[i]);
                    
                }
                for (var j = 0; j < userRoles.length; j++) {
                	if(userRoles[j].roleId!=281474976710665){
                		userRoleBox[j] = new Ext.form.Radio({
                            boxLabel: userRoles[j].roleName,
                            columnWidth: .2,
                            name: 'default_RoleId',
                            id: userRoles[j].roleId,
                            inputValue: userRoles[j].roleId
                        });
                	}
                    for (var k = 0; k < roles.length; k++) {
                        if (userRoles[j].roleId == roles[k].roleId) {
                            roleCheckbox[k].checked = true;
                            break;
                        }
                    }
                }
                
                user_defaultRole.add(userRoleBox);
                
                for (var n = 0; n < userRoles.length; n++) {
                    if (userRoles[n].roleId == defaultRole.roleId) {
                        userRoleBox[n].checked = true;
                    }
                }
                
                user_role.doLayout();
                user_defaultRole.doLayout();
                
                modify_user_form = new Ext.FormPanel({
                    border: false,
                    frame: true,
                    labelAlign: 'right',
                    labelWidth: 100,
                    id: 'modifyUser',
                    defaults: {
                        itemCls: 'form_text'
                    },
                    defaultType: 'textfield',
                    items: [{
                        xtype: 'hidden',
                        name: 'user.userId',
                        value: respText.user.userId
                    }, {
                        xtype: 'hidden',
                        name: 'user.gender',
                        value: respText.user.gender
                    }, {
                    	fieldLabel: '用户名',
                        value: respText.user.userName,
                        name : 'user.userName',
                        readOnly: true,
                        itemCls: 'form_text unedit'
                    },{
                        fieldLabel: '邮箱',
                        name: 'user.email',
                        allowBlank: false,
                        validator: function(value){
                            return verifyAddress(value);
                        },
                        invalidText: '输入的邮箱格式不合法,格式如:Json@163.com',
                        value: respText.user.email,
                        maxLength: 30,
                        maxLengthText : '邮箱最大长度不能超过30'
                    },{
                    
                        fieldLabel: '电话',
                        xtype: 'textfield',
                        name: 'user.telephone',
                        allowBlank: false,
                        value: respText.user.telephone,
                        regex:/^\d{4}-?\d{7}$|^[0-9]{4}-?[0-9]{8}$|^[0-9]{3}-?[0-9]{8}$/,
                        regexText:'输入的电话格式不合法,格式如:区号-号码[3-8,4-7,4-8]'
                    }, {
                        fieldLabel: '手机号',
                        xtype: 'textfield',
                        name: 'user.mobilePhone',
                        allowBlank: false,
                        value: respText.user.mobilePhone,
                        regex:/^1[0-9]{10}$/,
                        regexText:'输入的手机号码不合法,格式如:159****5678(11位)'
                    }, {
                        xtype: 'combo',
                        store: new Ext.data.SimpleStore({
                            data: [['1', '普通'], ['2', '秘密'], ['3', '机密'], ['5', '绝密']],
                            fields: ['value', 'text']
                        }),
                        fieldLabel: '涉密级别',
                        editable: false,
                        hiddenName: 'user.securityGrade',
                        value: respText.user.securityGrade,
                        mode: 'local',
                        triggerAction: 'all',
                        valueField: 'value',
                        displayField: 'text'
                    }, {
                        xtype: 'combo',
                        store: new Ext.data.SimpleStore({
                            data: [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5']],
                            fields: ['value', 'text']
                        }),
                        fieldLabel: '能力级别',
                        editable: false,
                        hiddenName: 'user.ability',
                        value: respText.user.ability,
                        mode: 'local',
                        triggerAction: 'all',
                        valueField: 'value',
                        displayField: 'text'
                    }, user_role, user_defaultRole],
                    buttons: [{
                        text: '确定',
                        type: 'submit',
                        handler: function(){
                            var flag = false;
                            
                            for (var m = 0; m < userRoleBox.length; m++) {
                                if (userRoleBox[m].checked) {
                                    flag = true;
                                }
                            }
                            
                            if (flag == false) {
                                Ext.Msg.show({
                                    title: '错误提示',
                                    msg: '必须选择默认角色',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.INFO,
                                    width: 200
                                });
                                return;
                            }
                            
                            if (modify_user_form.form.isValid()) {
                                modify_user_form.form.doAction('submit', {
                                    url: 'user_edit.action',// 文件路径
                                    method: 'post',// 提交方法post或get
                                    params: '',
                                    success: function(form, action){
                                        Ext.Msg.show({
                                            title: '提示',
                                            msg: '编辑成功!',
                                            buttons: Ext.Msg.OK,
                                            icon: Ext.Msg.INFO,
                                            width: 200
                                        });
                                        ds.reload();
                                        user_window.remove(Ext.getCmp('modifyUser'));
                                        user_window.close();
                                        roleCheckbox = new Array();
                                        userRoleBox = new Array();
                                    },
                                    failure: function(form, action){
                                        if (action.failureType == 'server') {
                                            Ext.Msg.show({
                                                title: '错误',
                                                msg: '编辑失败！',
                                                buttons: Ext.Msg.OK,
                                                icon: Ext.Msg.INFO,
                                                width: 200
                                            });
                                        }
                                        else 
                                    if (action.failureType == 'connect') {
                                        Ext.Msg.show({
											title : '连接错误',
											msg : '指定路径连接错误!',
											buttons : Ext.Msg.OK,
											icon : Ext.Msg.ERROR,
											width : 200
										});
                                    }
                                    else 
                                        if (action.failureType == 'client') {
                                            Ext.Msg.show({
												title : '提示',
												msg : '数据错误，非法提交',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                                        else {
                                            Ext.Msg.show({
												title : '警告',
												msg : '服务器数据传输错误',
												buttons : Ext.Msg.OK,
												icon : Ext.Msg.ERROR,
												width : 200
											});
                                        }
                                    }
                                });
                            }
                        }
                    }, {
                        text: '取消',
                        handler: function(){
                            userRoleBox = new Array();
                            user_window.remove(Ext.getCmp('modifyUser'));
                            user_window.close();
                            
                        }
                        
                    }]
                });
                
                
                
                var user_window = new Ext.Window({
                    title: '编辑用户信息',
                    width: 700,
                    iconCls: 'user_edit',
                    resizable: false,
                    constrain: true,
                    autoHeight: true,
                    modal: true,
                    closeAction: 'hide',
                    closable: false,
                    items: modify_user_form
                }).show();
            }
            else {
                Ext.Msg.show({
                    title: '错误提示',
                    msg: '查看用户详情失败！',
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR,
                    width: 200
                });
            }
        },
        failure: function(){
            Ext.Msg.show({
                title: '错误提示',
                msg: '修改失败！',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR,
                width: 200
            });
        }
    });
};

//时间格式转换
function formatTime(value, metadata, record){
    if (null == value) {
        return null;
    }
    else {
        return new Date(value).format('Y-m-d  H:i');
    }
}

var p_user = {
    id: 'user-search',
    border: false,
    layout: 'border',
    items: [grid]
};
Ext.getCmp('content-panel').add(p_user);
Ext.getCmp('content-panel').layout.setActiveItem('user-search');
